package pers.vic.basics.leetcode;

import java.util.Arrays;

/**
 * @description: 59. 螺旋矩阵 II  {@literal https://leetcode-cn.com/problems/spiral-matrix-ii/}
 * @author Vic.xu
 * @date: 2020/12/21 0021 10:21
 * @see J0054_M_54  54. 螺旋矩阵  二者思路一致
 */
public class J0059_M_GenerateMatrix {
    /*
    给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
        示例:
        输入: 3
        输出:
        [
         [ 1, 2, 3 ],
         [ 8, 9, 4 ],
         [ 7, 6, 5 ]
        ]
     */

    /**
     * 和54题思路一致，上右下左顺序存入
     */
    public static int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int total = n * n;
        int item = 1;

        int startRow = 0;
        int endRow = n - 1;
        int startColumn = 0;
        int endColumn = n - 1;
        while (item <= total) {

            //上行
            for (int i = startColumn; i <= endColumn; i++) {
                res[startColumn][i] = item++;
            }
            startRow++;

            //左列
            for (int i = startRow; i <= endRow; i++) {
                res[i][endColumn] = item++;
            }
            endColumn--;

            //下行
            if (startRow <= endColumn && startColumn <= endColumn) {
                for (int i = endColumn; i >= startColumn; i--) {
                    res[endRow][i] = item++;
                }
                endRow--;
            }

            //左列
            if (startRow <= endRow && startColumn <= endColumn) {
                for (int i = endRow; i >= startRow; i--) {
                    res[i][startColumn] = item++;
                }
                startColumn++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        for (int[] ints : generateMatrix(4)) {
            System.out.println(Arrays.toString(ints));
        }
    }

}
